package com.ruoyi.common.utils;

import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.File;
import java.util.Objects;

//@Slf4j
public class IpToAddressUtil {

    private static final String IP2REGION_TEMP_DIR = "/home/upload/";

//    @SneakyThrows
    public static String getRealAddressByIP(String ip) {
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        String dbPath = Objects.requireNonNull(AddressUtils.class.getResource("/ip2region/ip2region.xdb")).getPath();
        String[] obj = new String[0];
        try {
            File file = new File(dbPath);
            if (! file.exists()) {
                dbPath = IP2REGION_TEMP_DIR + "ip2region.xdb";
                file = new File(dbPath);
                FileUtils.copyInputStreamToFile(Objects.requireNonNull(AddressUtils.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.xdb")), file);
            }
            Searcher searcher = Searcher.newWithFileOnly(dbPath);
            String result = searcher.search(ip);
            if (StringUtils.isEmpty(result)) {
    //            log.error("获取地理位置异常 {}", ip);
                return "未知";
            }

            obj = result.split("\\|");
            searcher.close();
//            return result;
        } catch (Exception e) {
            e.printStackTrace();

        }
        StringBuilder sb =new StringBuilder();
        if(!"0".equals(obj[0])){
            sb.append(obj[0]+"-");
        }
        if(!"0".equals(obj[2])){
            sb.append(obj[2]+"-");
        }
        if(!"0".equals(obj[3])){
            sb.append(obj[3]+"-");
        }
        if(!"0".equals(obj[1])){
            sb.append(obj[1]+"-");
        }
        if(!"0".equals(obj[4])){
            sb.append(obj[4]+"-");
        }
        String str= sb.toString();
        str=str.substring(0,str.length()-1);
        return str;
//        if("0".equals(obj[3])){
//            return String.format("%s-%s", obj[0], obj[2], obj[3]);
//        }else {
//            return String.format("%s-%s-%s", obj[0], obj[2], obj[3]);
//        }

    }
}
